<?php

namespace app\modules\user\services;

use app\common\services\BaseService;
use app\components\pagination\Pagination;
use app\config\Constants;
use app\models\GoodsOrder;
use app\models\User;
use app\modules\index\services\ActivityService;
use app\modules\index\services\CalculateService;
use app\modules\index\services\DeliveryService;
use app\modules\user\forms\order\OrderForm;
use app\utils\QueueUtil;
use Carbon\Carbon;
use yii\base\UserException;
use yii\helpers\Json;

class GoodsOrderService extends BaseService{

    /**
     * 搜索
     * @param $user_id
     * @param $merchant_name
     * @param $order_no
     * @param $page
     * @param $pagesize
     * @return array|\yii\db\ActiveRecord[]
     */
    public static function search($user_id,$merchant_name,&$page,$pagesize){
        $query = GoodsOrder::find()
            ->select(['order_id','merchant_name','merchant_thumbnail','total_price','pay_method','status','pay_status','is_adjust','add_time'])
            ->andWhere(['user_id'=>$user_id])
            ->orderBy(['add_time'=>SORT_DESC]);

        if(!empty($merchant_name)){
            $query->andWhere(['like','merchant_name',$merchant_name]);
        }
        if(!empty($order_no)){
            $query->andWhere(['like','order_no',$order_no]);
        }

        $page = new Pagination(['totalCount' => $query->count(), 'pageSize' => $pagesize]);
        $query->offset($page->getOffset());
        $query->limit($page->getLimit());

        return $query->all();
    }

    /**
     * 创建
     * @param OrderForm $form
     * @return array|bool
     * @throws \Throwable
     */
    public static function create(OrderForm $form){
        if(!$form->validate()){
            self::setError($form->getFirstFieldError());
            return false;
        }
        /**
         * @var User $user
         */
        $user = \Yii::$app->getModule("user")->get("user")->getIdentity();
        if($user->status == Constants::STATUS_PROHIBIT){
            self::setError(\Yii::t("app","账户已被冻结,请联系客服!"));
            return false;
        }

        $merchant = MerchantService::getInfoById($form->merchant_id);
        if(!$merchant){
            self::setError(\Yii::t("app","店铺不存在"));
            return false;
        }
        if($merchant->status == Constants::STATUS_PROHIBIT){
            self::setError(\Yii::t("app","商户已被冻结!"));
            return false;
        }
        $range = explode("-",$merchant->business_time);
        if(date("H") < $range[0] && date("H") > $range[2]){
            self::setError(\Yii::t("app","商户已打烊!"));
            return false;
        }

        $info = InfoService::getInfoById();
        $flag = false;
        if($merchant->customer_type == Constants::CUSTOMER_TYPE_BOTH || $merchant->customer_type == Constants::CUSTOMER_TYPE_STORE){
            if(isset($info['store']) && $info['store']->is_verify == Constants::VERIFY_SUCCESS){
                $flag = true;
            }
        }
        if($merchant->customer_type == Constants::CUSTOMER_TYPE_BOTH || $merchant->customer_type == Constants::CUSTOMER_TYPE_USER){
            if(isset($info['user']) && $info['user']->is_verify == Constants::VERIFY_SUCCESS){
                $flag = true;
            }
        }
        if(!$flag){
           self::setError(\Yii::t("app","请先完成认证再下单!"));
           return false;
        }

        //计算商品价格
        $goods_data = CalculateService::calc($form->merchant_id,$form->goods_item);
        if(!$goods_data) {
            throw new UserException(CalculateService::getError());
        }
        //计算配送费,当为堂食或自提无需配送费
        if(strpos($form->delivery_time,'自提') !== false){
            $delivery_data = [
                'distance'=>0,
                'delivery_price'=>0,
            ];
        }else{
            $delivery_data = DeliveryService::calc($form->merchant_id,$form->lng_lat);
        }
        //计算活动最优惠价格
        $act_data = ActivityService::calc($goods_data['total_price'],$form->merchant_id);
        $total_price = $goods_data['total_price'] + $delivery_data['delivery_price'];

        foreach($goods_data['goods_item'] as $k=>$v){
            //将goods_count改为new_count
            $goods_data['goods_item'][$k]['new_count'] = $goods_data['goods_item'][$k]['goods_count'];
            unset($goods_data['goods_item'][$k]['goods_count']);
        }

        $model = new GoodsOrder();
        $model->setAttributes($form->getAttributes(),false);
        $model->setAttribute("merchant_name",$merchant->merchant_name);
        $model->setAttribute("merchant_thumbnail",$merchant->thumbnail);
        $model->setAttribute("merchant_desc",$merchant->merchant_desc);
        $model->setAttribute("merchant_phone",$merchant->merchantInfo->contact_phone);
        $model->setAttribute("goods_item",Json::encode($goods_data['goods_item']));
        $model->setAttribute("total_price",$total_price);
        $model->setAttribute("delivery_price",$delivery_data['delivery_price']);
        $model->setAttribute("coupon_price",$act_data['coupon_price']);
        $model->setAttribute("real_price",$total_price - $act_data['coupon_price']);
        $model->setAttribute("activity_info",!empty($act_data['act_info']) ? $act_data['act_info']['act_name'] : "");
        $model->setAttribute("pay_method",$form->payment);
        $model->setAttribute("add_time",date("Y-m-d H:i:s"));

        //货到付款
        if($form->payment == Constants::PAY_DELIVERY){
            $model->setAttribute("status",Constants::ORDER_WAIT);
            $model->insert() !== false && QueueUtil::fanout(Constants::MSG_TYPE_ORDER,Constants::ORDER_WAIT,['order_no'=>$form->order_no]);
        }else{
            $model->setAttribute("status",Constants::ORDER_WAIT_PAYMENT);
            $model->insert();
        }

        return [
            'order_id'=>$model->order_id,'order_no'=>$model->order_no
        ];
    }

    /**
     * 获取信息
     * @param $user_id
     * @param $id
     * @return null|GoodsOrder
     */
    public static function getInfoById($user_id,$id){
        return GoodsOrder::findOne(['user_id'=>$user_id,'order_id'=>$id]);
    }

    /**
     * 取消
     * @param $user_id
     * @param $id
     * @return bool
     * @throws \Throwable
     * @throws \yii\db\StaleObjectException
     */
    public static function cancel($user_id,$id){
        $model = GoodsOrder::findOne(['user_id'=>$user_id,'order_id'=>$id]);
        if(!$model){
            self::setError(\Yii::t("app","订单不存在"));
            return false;
        }
        if(in_array($model->status,[Constants::ORDER_CANCEL,Constants::ORDER_ACCEPT,Constants::ORDER_COMPLETE,Constants::ORDER_ADJUST])){
            self::setError(\Yii::t("app","订单状态错误"));
            return false;
        }
        $model->setAttribute("status",Constants::ORDER_CANCEL);
        $model->setAttribute("pay_status",Constants::PAY_STATUS_CANCEL);
        $model->setAttribute("end_time",Carbon::now()->toDateTimeString());
        return $model->update() !== false && QueueUtil::fanout(Constants::MSG_TYPE_ORDER,Constants::ORDER_CANCEL,['order_no'=>$model->order_no,'cancel'=>Constants::USER]);
    }
}